package com.qyhl.module_practice.study;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.entity.news.SpecialDetailBean;
import com.qyhl.webtv.commonlib.entity.news.UnionBean;
import com.qyhl.webtv.commonlib.utils.ItemSkipUtils;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


@Route(path = ARouterPathConstant.PRACTICE_STUDY)
public class PracticeStudyActivity extends BaseActivity implements PracticeStudyContract.PracticeStudyView {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private PracticeStudyPresenter mPresenter;

    private List<SpecialDetailBean> mDataList = new ArrayList<>();

    private List<UnionBean> mNewDataList = new ArrayList<>();

    private CommonAdapter commonAdapter;

    private CommonAdapter<NewsBean> newsBeanCommonAdapter;

    private List<UnionBean> sectionList;

    List<GlobalNewsBean> indexList;

    private String sectionId;

    private boolean isNew;


    @Override
    protected int getContentView() {
        return R.layout.practice_activity_study;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);
        mPresenter = new PracticeStudyPresenter(this);
        sectionId = getIntent().getStringExtra("id");
        String titleName = getIntent().getStringExtra("title");
        isNew = getIntent().getBooleanExtra("isNew", false);
        title.setText(titleName);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(false);

        recycleView.setLayoutManager(new LinearLayoutManager(this));

        if (isNew) {
            recycleView.setAdapter(commonAdapter = new CommonAdapter<UnionBean>(this, R.layout.practice_item_study_new, mNewDataList) {
                @Override
                protected void convert(ViewHolder holder, UnionBean bean, int position) {
                    holder.setText(R.id.title, bean.getName());
                    ImageView cover = holder.getView(R.id.cover);

                    Glide.with(PracticeStudyActivity.this)
                            .load(bean.getLogo())
                            .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                            .into(cover);
                }
            });
        } else {
            recycleView.setAdapter(commonAdapter = new CommonAdapter<SpecialDetailBean>(this, R.layout.practice_item_study, mDataList) {
                @Override
                protected void convert(ViewHolder holder, final SpecialDetailBean bean, int position) {
                    holder.setText(R.id.title, bean.getName());

                    holder.setOnClickListener(R.id.more, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", bean.getSection());
                            bundle.putString("title", bean.getName());
                            RouterManager.router(ARouterPathConstant.NEWS_LIST, bundle);
                        }
                    });

                    RecyclerView recyclerView = holder.getView(R.id.recycle_view);

                    recyclerView.setLayoutManager(new GridLayoutManager(PracticeStudyActivity.this, 2));
                    recyclerView.setAdapter(newsBeanCommonAdapter = new CommonAdapter<NewsBean>(PracticeStudyActivity.this, R.layout.practice_item_study_two, bean.getTopicNews()) {
                        @Override
                        protected void convert(ViewHolder holder, NewsBean newsBean, int position) {
                            holder.setText(R.id.title, newsBean.getTitle());
                            RoundedImageView cover = holder.getView(R.id.cover);
                            Glide.with(PracticeStudyActivity.this)
                                    .load(newsBean.getLogo())
                                    .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                                    .into(cover);
                        }
                    });

                    newsBeanCommonAdapter.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                            setNews(bean.getTopicNews());
                            ItemSkipUtils.getInstance().itemSkip(indexList.get(position), PracticeStudyActivity.this, view);
                        }

                        @Override
                        public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                            return false;
                        }
                    });
                }
            });
        }
        mPresenter.getSectionList(sectionId, isNew);
    }

    @Override
    protected void setListener() {
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getSectionList(sectionId, isNew);
            }
        });

        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getSectionList(sectionId, isNew);
            }
        });

        if (isNew) {
            commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", mNewDataList.get(i).getId());
                    bundle.putString("title", mNewDataList.get(i).getName());
                    RouterManager.router(ARouterPathConstant.PRACTICE_STUDY_NEW, bundle);
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                    return false;
                }
            });
        }
    }

    @Override
    public void setSection(List<UnionBean> beanList) {
        if (isNew) {
            loadMask.setStatus(LoadingLayout.Success);
            loadMask.setReloadButtonText("点击重试~");

            mNewDataList.clear();
            mNewDataList.addAll(beanList);
            commonAdapter.notifyDataSetChanged();
        } else {
            StringBuilder mSections = new StringBuilder();
            sectionList = beanList;
            for (int i = 0; i < beanList.size(); i++) {
                if (i == (beanList.size() - 1)) {
                    mSections.append(beanList.get(i).getId());
                } else {
                    mSections.append(beanList.get(i).getId()).append(",");
                }
            }

            mPresenter.getData(mSections.toString());
        }
    }

    @Override
    public void setData(List<SpecialDetailBean> beanList) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        for (int i = 0; i < beanList.size(); i++) {
            beanList.get(i).setName(sectionList.get(i).getName());
        }
        mDataList.clear();
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();

    }

    @Override
    public void setError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");
        if (!NetUtil.isNetworkAvalible(this)) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }


    @OnClick(R2.id.back_btn)
    public void onViewClicked() {
        finish();
    }

    /**
     * 设置新闻
     */
    private void setNews(List<NewsBean> beanList) {
        indexList = new ArrayList<>();

        //数据类型转换
        for (int i = 0; i < beanList.size(); i++) {
            NewsBean bean = beanList.get(i);
            boolean hasPicture = StringUtils.isPictureSuccess(bean.getLogo());
            String type = "", pOne = "", pTwo = "", pThree = "";
            int style = 0;
            switch (bean.getType()) {
                case "1"://普通新闻
                    type = "1";
                    switch (bean.getPluralPicsFlag()) {
                        case 0:
                            style = bean.getCommonStyle();
                            break;
                        case 1://三图
                            style = 4;
                            break;
                        case 2:
                            style = 3;
                            break;
                        default:
                            style = bean.getCommonStyle();
                            break;
                    }
                    break;
                case "2"://图片新闻
                    type = "2";
                    break;
                case "3"://直播
                    type = "9";
                    break;
                case "4"://标题新闻
                    type = "8";
                    break;
                case "5"://视频新闻
                    type = "3";
                    style = bean.getVideoStyle();
                    break;
                case "8"://互动直播
                    bean.setID(bean.getRoomId());//将roomId设置成通用Id
                    type = "5";
                    break;
                case "101"://抓取新闻
                    type = "10";
                    break;
                default:
                    break;
            }
            indexList.add(new GlobalNewsBean(bean.getTitle(), bean.getID(), bean.getRedirectURL(), bean.getLogo(), style, bean.getPublishDate(), type, Integer.parseInt(bean.getHitCount()), bean.getSource(), bean.getCatalogID(), hasPicture, pOne, pTwo, pThree, bean.getLivetype(), bean.getCommentCount()));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_STUDY);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_STUDY);
    }
}
